﻿# -*- coding: utf-8 -*-
import sys, os
from twisted.internet import protocol, reactor
from twisted.protocols import basic
import locale

import Config, User, Room
from Log import *
from Utils import *

sys.path.append( Config.get("blink.plugin_path") )

class BlinkFactory(protocol.ServerFactory):
    protocol = User.BlinkUser
    
    def startFactory(self):
        plugin = Config.get("CommonRoom.plugin").strip()
        Room.BlinkRoom.commonRoom =  Room.BlinkRoom( name=Config.get("CommonRoom.name") , parent=None ,plugin=plugin)
        autocreate_rooms = Config.get("StaticRoom.static_room")
        dbg("createing static rooms:" + autocreate_rooms)
        for r in [rr.strip() for rr in autocreate_rooms.split(",") if rr.strip() !=''] :
            name   = r
            hassub = isTrue(Config.get("StaticRoom."+name+".hassub"))
            max    = int(Config.get("StaticRoom."+name+".max_users"))
            plugin = Config.get("StaticRoom."+name+".plugin").strip()
            Room.BlinkRoom.commonRoom.createSubRoom(name=r, userCreator=None, canCreateSub=hassub, destroyOnEmpty=False, maxusers=max, plugin=plugin)

dbg("blinking...")

class runner(object) :
    def __init__(self,r) :
        self.runner = r
        self.pidfile = "BlinkServer.pid"
        self.stdin = '/dev/null'
        self.stdout = 'log/out'
        self.stderr = 'log/err'
        
    def run(self) :
        self.runner.listenTCP( int(Config.get("blink.port")) , BlinkFactory())
        self.runner.run()

rr = runner(reactor)

if( Config.get("Blink.daemon") .lower() in ['true','yes','enable','1']) :
    try :
        import Daemon
        print "run as daemon"
        d = Daemon.Daemon(rr)
    except :
        print "daemon failed. attemp to run with no-daemon."

rr.run()
